package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.INewsDao;
import com.cn.wanxi.dao.impl.NewsDaoImpl;
import com.cn.wanxi.model.NewsModel;
import com.cn.wanxi.model.PageModel;
import com.cn.wanxi.service.INewsService;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Map;

public class NewsServiceImpl implements INewsService {
    INewsDao newsDao = new NewsDaoImpl();
    @Override
    public int addNews(NewsModel newsModel) {
        return newsDao.addNews(newsModel);
    }

    @Override
    public int deleteNews(int id) {
        return newsDao.deleteNews(id);
    }

    @Override
    public int editNews(NewsModel newsModel) {
        return newsDao.editNews(newsModel);
    }

    @Override
    public List<NewsModel> getNewsList(Map<String ,Object> map) {
        int page = (int) map.get("page");
        List<NewsModel> newsList = null;
        //只缓存第一页新闻数据
        if (page == 1){
            try {
                Jedis jedis = new Jedis();
                if (jedis.exists("news_id")){
                    newsList = newsDao.getNewsListByRedis();
                }else {
                    newsList = newsDao.getNewsList(map);
                    newsDao.setNewsListInRedis(newsList);
                }
            }catch (Exception e){
                newsList = newsDao.getNewsList(map);
            }
        }else
            newsList = newsDao.getNewsList(map);
        return newsList;
    }

    @Override
    public NewsModel getNews(int id) {
        return newsDao.getNews(id);
    }

    @Override
    public PageModel<NewsModel> getAllNews(Map<String,Object> map) {
        PageModel pager = new PageModel();
        pager.setList(newsDao.getAllNews(map));
        pager.setTotal(newsDao.getNewsCount(map));
        return pager;
    }

    @Override
    public int updateShow(int id, int show) {
        NewsModel newsModel = new NewsModel();
        newsModel.setIsShow(show);
        newsModel.setId(id);
        return newsDao.updateShow(newsModel);
    }
}
